<template>
  <div class="iot">
    <!-- 顶部子模块切换 -->
    <!-- <div class='child-menu flex-x main-center cross-center'>
      <span
        class='child-menu-item'
        :class='{ active: currentChildItem === 0 }'
        @click='handleChildMenuItemClick(0)'
      >查楼栋</span
      >
      <div></div>
      <span
        class='child-menu-item'
        :class='{ active: currentChildItem === 1 }'
        @click='handleChildMenuItemClick(1)'
      >查属性</span
      >
    </div> -->
    <div
      class="left"
      :class="{ 'left-hide': leftHide }"
      ref="leftRef"
    >
      <div class="left-panel">
        <el-scrollbar>
          <div class="bimNav-title">
            <div
              @click="toolItemClickHandle(item)"
              v-for="(item, index) in toolData"
              :key="index"
              :class="{
                'is-active': activeTool === item.value
              }"
            >
              {{ item.label }}
              <p class="line"></p>
            </div>
          </div>
          <div class="line-split"></div>
          <!--          :multiDetailData="multiDetailData"-->
          <!--          :multiDetailIndex="multiDetailIndex"-->
          <!--          @floorClick="handleFloorClick"-->
          <!--          @domainClick="handleDomainClick"-->
          <component
            v-if="activeTool"
            :is="activeTool"
            :activeStage="activeStage"
            :bimNumber="bimNumber"
            style="width: 100%"
          />
          <div v-else>暂无数据！</div>
        </el-scrollbar>
      </div>
      <div
        class="left-close"
        @click="leftHide = !leftHide"
      ></div>

      <div
        class="bar"
        @mousedown.prevent="handleLeftMouseDown"
      ></div>
    </div>
  </div>
</template>

<script>
import Property from './components/property'
import Device from './components/device'
import Domain from './components/domain'
// import Properties from './components/properties'
import { getAction } from '@/utils/helper'
import { topicDefaultList } from '@/api/tree'
import { retrieveDataServiceById } from '@/api/multiple-dataservice'

let _layerManager

export default {
  name: 'BIM',
  inject: ['viewerId'],
  components: {
    Property,
    Device,
    Domain
    // Properties
  },
  data() {
    return {
      currentChildItem: 0,
      leftX: '',
      leftWidth: '',
      rightX: '',
      rightWidth: '',
      // 当前服务类型
      treeTypeName: 'BIM',
      treeTypeId: '2',
      // 关键词 前端过滤树形结构
      keyword: '',
      filterKeyword: '',
      // 隐藏侧边
      leftHide: true,
      rightHide: true,
      // multiDetailData: [],
      // multiDetailIndex: -1,
      options: [],
      value: '',
      // _viewer: null,
      // _layerManager: null,
      queryResultData: undefined,
      layerCamera: {},
      toolData: [
        {
          label: '资产信息',
          value: 'Property'
        },
        {
          label: '监测设备',
          value: 'Device'
        },
        {
          label: '功能分区',
          value: 'Domain'
        }
        // {
        //   label: '属性查询',
        //   value: 'Properties'
        // }
      ],
      activeTool: 'Property',
      showType: 1,
      // 配置的资产id
      activeStage: {},
      bimNumber: ''
    }
  },
  computed: {
    defaultViewId() {
      return this.$store.state.layer.defaultViewId
    }
  },
  async created() {
    const { layerManager } = await getAction(
      this.defaultViewId
    )
    _layerManager = layerManager
    // _viewer = viewer

    this.$bus.$on('togglePanel', (flag) => {
      this.leftHide = flag
    })

    this.$bus.$on('modelSearchCode', (bimNumber) => {
      console.log('接收到BIM_NUMBER属性', bimNumber)
      this.bimNumber = bimNumber
    })

    this.$bus.$on('activeDataChange', (val) => {
      this.activeStage = val
      console.log('收到activeData改变', val)
    })

    // 接收到S3M构建点击查询返回的属性
    this.$bus.$on(
      'fetchedFeatureProperties',
      (properties) => {
        console.log('查询到的属性', properties)

        Object.keys(properties.detailData).forEach(
          (item) => {
            if (item.toLowerCase() === 'bim_number') {
              this.bimNumber = properties.detailData[item]
            }
          }
        )

        // this.multiDetailData = [properties]
        // this.multiDetailIndex = 0
        this.leftHide = false
        // this.activeTool = 'Properties'
        setTimeout(() => {
          this.activeTool = 'Property'
        }, 200)
      }
    )

    topicDefaultList('shuziluansheng').then(async (res) => {
      if (res.success && res.data) {
        for await (const item of res.data.reverse()) {
          item.dataList = await this.getDataList(item.pkid)
          if (!item.dataList.length) {
            return
          }
          item.serviceUrl = item.dataList[0].serviceUrl
          item.signService = item.dataList[0].signService
          item.currentDataIndex = 0
          this.$bus.$emit('showDataList', item)
          await _layerManager.addAsync(item)
        }
      }
    })
  },
  methods: {
    handleChildMenuItemClick(index) {
      this.currentChildItem = index
    },
    onSearchChange(newValue) {
      this.filterKeyword = newValue
    },
    // 右侧工具栏点击
    toolItemClickHandle(data) {
      const { value } = data
      this.activeTool =
        this.activeTool === value ? undefined : value
      this.clearLayerStyle() // 清除楼样式
      // console.log('toolItemClickHandle', data)
    },
    // 楼层点击回调
    // handleFloorClick(item) {
    //   const value = item.floorName
    //   const activeStage = this.activeStage
    //   if (!activeStage) return
    //   if (
    //     !activeStage.dataService ||
    //     activeStage.dataService === ''
    //   ) {
    //     // this.$message('没有挂载数据源,暂无图层效果');
    //     return
    //   }
    //   this.getFloorGroup(value, activeStage)
    // },
    // 查询楼层组件
    // getFloorGroup(value, selLayer) {
    //   let { dataService } = selLayer
    //   dataService = decodeURI(dataService)
    //   // dataService = 'http://101.254.248.164:8090/iserver/services/data-ChengDu_bim2/rest/data/datasources/bimfortest2';
    //   const arr = dataService.split('/datasources/')
    //   const dataUrl = arr[0]
    //   const dataSource = arr[1]
    //   // console.log('dataService', dataUrl, dataSource);
    //   const viewerLayerData = _layerManager._layers.get(
    //     this.activeStage.pkid
    //   ).layer
    //   viewerLayerData.forEach((v) => {
    //     const { _name, _id } = v
    //     v.releaseSelection()
    //     v.removeAllObjsColor()
    //     if (value === '0') return
    //     const newName = _name.split('@')
    //     v.setQueryParameter({
    //       url: dataUrl,
    //       dataSourceName: dataSource,
    //       dataSetName: newName[0],
    //       hasGeometry: false
    //     })
    //     // 查询所在图层组件
    //     const queryParameters =
    //       new SuperMap.GetFeaturesBySQLParameters({
    //         queryParameter: {
    //           name: newName[0],
    //           attributeFilter: `FLOOR_NUMBER ='${value}'`,
    //           fields: ['SmID']
    //         },
    //         toIndex: -1,
    //         maxFeatures: 99999,
    //         datasetNames: [`${dataSource}:${newName[0]}`],
    //         hasGeometry: false
    //       })
    //     L.supermap
    //       .featureService(v.queryParameter.url)
    //       .getFeaturesBySQL(queryParameters, (res) => {
    //         const SmIDArray = []
    //         console.log('sql', res)
    //         res.result.features.features.forEach((e) => {
    //           SmIDArray.push(e.properties.SmID)
    //         })
    //         this.setFloorGroupStyle(
    //           v,
    //           SmIDArray,
    //           newName[0],
    //           dataSource
    //         )
    //       })
    //   })
    // },
    // 设置楼层组件样式
    // setFloorGroupStyle(v, SmIDArray, name, dataSource) {
    //   // 查询所有组件
    //   const targetQueryParameters =
    //     new SuperMap.GetFeaturesBySQLParameters({
    //       queryParameter: {
    //         name: name,
    //         fields: ['SmID']
    //       },
    //       toIndex: -1,
    //       maxFeatures: 99999,
    //       datasetNames: [`${dataSource}:${name}`],
    //       hasGeometry: false
    //     })
    //   L.supermap
    //     .featureService(v.queryParameter.url)
    //     .getFeaturesBySQL(targetQueryParameters, (res) => {
    //       const allSmIDArray = []
    //       res.result.features.features.forEach((e) => {
    //         allSmIDArray.push(e.properties.SmID)
    //       })
    //       const xorArrayData = _.xor(
    //         SmIDArray,
    //         allSmIDArray
    //       )
    //       v.setObjsColor(
    //         xorArrayData,
    //         new Cesium.Color(255, 255, 255, 0)
    //       )
    //     })
    // },
    // 功能区选择回调
    // handleDomainClick(item) {
    //   const value = item.name
    //   const activeStage = this.activeStage
    //   // console.log('handleDomainClick', value, activeStage)
    //   if (!activeStage) return
    //   if (
    //     !activeStage.dataService ||
    //     activeStage.dataService === ''
    //   ) {
    //     // this.$message('没有挂载数据源,暂无图层效果');
    //     return
    //   }
    //   this.getDomainGroup(value, activeStage)
    // },
    // 查询楼层组件
    // getDomainGroup(value, selLayer) {
    //   let { dataService } = selLayer
    //   dataService = decodeURI(dataService)
    //   // dataService = 'http://101.254.248.164:8090/iserver/services/data-ChengDu_bim2/rest/data/datasources/bimfortest2';
    //   const arr = dataService.split('/datasources/')
    //   const dataUrl = arr[0]
    //   const dataSource = arr[1]
    //   // console.log('dataService', dataService, dataUrl, dataSource);
    //   const viewerLayerData = _layerManager._layers.get(
    //     this.activeStage.pkid
    //   ).layer
    //   viewerLayerData.forEach((v) => {
    //     const { _name, _id } = v
    //     v.releaseSelection()
    //     v.removeAllObjsColor()
    //     if (value === '0') return
    //     const newName = _name.split('@')
    //     v.setQueryParameter({
    //       url: dataUrl,
    //       dataSourceName: dataSource,
    //       dataSetName: newName[0],
    //       hasGeometry: false
    //     })
    //     // 查询所在图层组件
    //     const queryParameters =
    //       new SuperMap.GetFeaturesBySQLParameters({
    //         queryParameter: {
    //           name: newName[0],
    //           attributeFilter: `TYPE ='${value}'`,
    //           fields: ['SmID']
    //         },
    //         toIndex: -1,
    //         maxFeatures: 99999,
    //         datasetNames: [`${dataSource}:${newName[0]}`],
    //         hasGeometry: false
    //       })
    //     L.supermap
    //       .featureService(v.queryParameter.url)
    //       .getFeaturesBySQL(queryParameters, (res) => {
    //         const SmIDArray = []
    //         console.log('sql', res)
    //         res.result.features.features.forEach((e) => {
    //           SmIDArray.push(e.properties.SmID)
    //         })
    //         this.setFloorGroupStyle(
    //           v,
    //           SmIDArray,
    //           newName[0],
    //           dataSource
    //         )
    //       })
    //   })
    // },
    // 设置楼层组件样式
    // setDomainGroupStyle(v, SmIDArray, name, dataSource) {
    //   // 查询所有组件
    //   const targetQueryParameters =
    //     new SuperMap.GetFeaturesBySQLParameters({
    //       queryParameter: {
    //         name: name,
    //         fields: ['SmID']
    //       },
    //       toIndex: -1,
    //       maxFeatures: 99999,
    //       datasetNames: [`${dataSource}:${name}`],
    //       hasGeometry: false
    //     })
    //   L.supermap
    //     .featureService(v.queryParameter.url)
    //     .getFeaturesBySQL(targetQueryParameters, (res) => {
    //       const allSmIDArray = []
    //       res.result.features.features.forEach((e) => {
    //         allSmIDArray.push(e.properties.SmID)
    //       })
    //       const xorArrayData = _.xor(
    //         SmIDArray,
    //         allSmIDArray
    //       )
    //       v.setObjsColor(
    //         xorArrayData,
    //         new Cesium.Color(255, 255, 255, 0)
    //       )
    //     })
    // },
    // 清除图层样式
    // clearLayerStyle() {
    //   const activeStage = this.activeStage
    //   if (!activeStage) return
    //   const viewerLayerData =
    //     _viewer.scene._layers._layers._array
    //   viewerLayerData.forEach((v) => {
    //     // v.releaseSelection()
    //     v.removeAllObjsColor()
    //   })
    // },
    handleLeftMouseDown(e) {
      this.leftX = e.clientX
      this.leftWidth = this.$refs.leftRef.offsetWidth
      document.documentElement.addEventListener(
        'mousemove',
        this.leftMove
      )
      document.documentElement.addEventListener(
        'mouseup',
        this.leftEnd
      )
    },
    leftMove(e) {
      let width = this.leftWidth + e.clientX - this.leftX
      width = width >= 500 ? 500 : width < 340 ? 340 : width
      this.$refs.leftRef.style['min-width'] = `${width}px`
      this.$refs.leftRef.style.setProperty(
        '--scroll-width',
        `${-width}px`
      )
    },
    leftEnd() {
      document.documentElement.removeEventListener(
        'mousemove',
        this.leftMove
      )
      document.documentElement.removeEventListener(
        'mouseup',
        this.leftEnd
      )
    },
    handleRightMouseDown(e) {
      this.rightX = e.clientX
      this.rightWidth = this.$refs.rightRef.offsetWidth
      document.documentElement.addEventListener(
        'mousemove',
        this.rightMove
      )
      document.documentElement.addEventListener(
        'mouseup',
        this.rightEnd
      )
    },
    rightMove(e) {
      let width =
        this.rightWidth + (this.rightX - e.clientX)
      width = width >= 500 ? 500 : width < 400 ? 400 : width
      this.$refs.rightRef.style['min-width'] = `${width}px`
      this.$refs.rightRef.style.setProperty(
        '--scroll-width',
        `${-(width - 47 - 1)}px`
      )
    },
    rightEnd() {
      document.documentElement.removeEventListener(
        'mousemove',
        this.rightMove
      )
      document.documentElement.removeEventListener(
        'mouseup',
        this.rightEnd
      )
    },
    // 获取服务的地图服务列表
    async getDataList(pkid) {
      const list = []
      await retrieveDataServiceById({
        pageIndex: 1,
        pageSize: 999,
        serviceId: pkid
      }).then((res) => {
        if (res.success) {
          if (res.data && res.data.length) {
            // 将配置的数据列表赋给原始数据
            list.push(...res.data)
          } else {
            this.$message.warning('该服务未配置数据')
          }
        } else {
          this.$message.error(
            res.message || '服务数据查询失败'
          )
        }
      })
      return list
    }
  },
  watch: {
    activeStage: {
      handler() {
        this.leftHide = true
        this.bimNumber = ''
        // this.multiDetailData = []
        // this.multiDetailIndex = -1
      },
      deep: true
    }
  }
}
</script>

<style lang="scss" scoped>
.child-menu {
  position: absolute;
  left: 50%;
  top: 95px;
  width: 175px;
  height: 38px;
  transform: translateX(-50%);
  background-image: url('~@/assets/img/child-menu-background.png');
  background-repeat: no-repeat;
  background-size: cover;

  & div {
    width: 1px;
    height: 14px;
    background-color: white;
    opacity: 0.3;
    margin: 0 5px;
  }

  & span {
    font-size: 14px;
    color: #d2e6f0;
    padding: 0 10px;
    cursor: pointer;

    &.active {
      font-weight: bold;
      color: white;
      background-image: url('~@/assets/img/background-cockpit-menu-item-active.png');
      background-repeat: no-repeat;
      background-size: 100% 100%;
    }
  }
}

.left {
  position: fixed;
  left: 0;
  top: 60px;
  width: 340px;
  height: calc(100% - 60px);
  padding: 14px 0 14px 14px;
  background-color: transparent;
  transition: all 1s;
  --scroll-width: -340px;

  &-panel {
    height: 100%;
    background-color: rgba(7, 13, 35, 0.5);

    ::v-deep {
      .el-scrollbar {
        height: 100%;

        &__wrap {
          overflow-x: hidden;
        }

        &__view {
          display: flex;
          flex-direction: column;
          height: 100%;
          padding-right: 8px;
        }
      }
    }
  }

  //::v-deep {
  //  // scrollbar横向滚动条
  //  .el-scrollbar__wrap {
  //    overflow-x: hidden;
  //  }
  //}

  &-content {
    width: calc(100% - 32px);
    height: 100%;
    margin: 20px auto;

    &-title:not(:first-child) {
      padding-top: 26px;
      border-top: 1px solid rgba(255, 255, 255, 0.2);
    }

    &-title {
      padding-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      background: url('../../../assets/bim/bim_right_top@2x.png');

      &-l {
        width: 4px;
        height: 12px;
        background: linear-gradient(0deg, #bcf8ff, #40ebff);
        border-radius: 0 0 0 0;
        margin-right: 10px;
      }

      &-r {
        word-break: keep-all;
        font-size: 14px;
        font-weight: 800;
        background: linear-gradient(
          0deg,
          #bcf8ff 0%,
          #40ebff 100%
        );
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    }

    &-echart {
      width: 100%;
      padding: 10px 0;
    }

    &-query {
      display: flex;
      align-items: center;
      justify-content: space-between;

      & span {
        word-break: keep-all;
        font-size: 14px;
        font-weight: 400;
        color: #ffffff;
      }

      ::v-deep {
        .el-input__inner {
          background-color: transparent;
          border: 1px solid rgba(255, 255, 255, 0.4);
          border-radius: 0;
          height: 30px;
          line-height: 30px;
        }

        .el-input__icon {
          line-height: 30px;
        }
      }
    }
  }

  &-panel {
    height: 100%;
    background-color: rgba(7, 13, 35, 0.5);

    ::v-deep {
      .el-scrollbar {
        height: 100%;

        &__wrap {
          overflow-x: hidden;
        }

        &__view {
          padding-right: 8px;
        }
      }
    }

    .header {
      padding: 31px 11px 48px 15px;

      &-icon {
        position: relative;
        width: 60px;
        height: 60px;
        margin-right: 3px;

        img.background {
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
        }

        img.center {
          width: 34px;
          height: 34px;
          z-index: 1;
        }
      }

      &-title {
        font-size: 14px;
        font-weight: 400;
        color: white;
      }

      .area {
        font-size: 20px;
        font-weight: bold;
        color: white;
      }

      .unit {
        font-size: 14px;
        font-weight: 400;
        color: white;
      }
    }

    .line-separator {
      width: 100%;
      padding: 0 8px;
    }

    .chart-wrapper {
      padding: 29px 10px 60px 10px;

      &:last-of-type {
        padding-bottom: 0;
      }

      &-content {
        margin-top: 20px;

        .chart {
          width: 50% !important;
        }
      }

      .legend {
        &:not(:last-of-type) {
          margin-bottom: 13px;
        }

        &-round-icon {
          width: 7px;
          height: 7px;
          margin-right: 3px;
          border-radius: 50%;

          &.blue {
            background-color: #696dff;
          }

          &.light-blue {
            background-color: #00ffff;
          }

          &.green {
            background-color: #00d075;
          }

          &.orange {
            background-color: #ffa862;
          }

          &.yellow {
            background-color: #ffdda2;
          }
        }

        &-title {
          font-size: 14px;
          font-weight: 400;
          color: white;
          margin-right: 6px;
        }

        &-value {
          font-size: 14px;
          font-weight: bold;
          color: white;
        }
      }

      .chart-title {
        font-size: 12px;
        font-weight: 400;
        color: #d2e6f0;
        align-self: flex-end;
        margin-top: 20px;
      }
    }

    .title {
      &-prefix {
        position: relative;
        top: 2px;
        width: 6px;
        height: 16px;
        margin-right: 5px;
        object-fit: fill;
      }

      span {
        font-size: 14px;
        font-weight: 800;
        line-height: 14px;
        background: linear-gradient(
          180deg,
          white 0%,
          #a4bbdd 100%
        );
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    }
  }

  &-hide {
    left: var(--scroll-width);

    & > .left-close {
      background-color: red;

      &::before,
      &::after {
        transform-origin: 6px 1px;
      }
    }
  }

  &-close {
    position: absolute;
    left: 100%;
    top: 50%;
    transform: translateY(-50%);
    width: 14px;
    height: 44px;
    cursor: pointer;
    background: #192f3d;
    opacity: 0.7;

    &::before,
    &::after {
      content: '';
      position: absolute;
      width: 7px;
      height: 2px;
      background: #fff;
      top: 50%;
      left: 50%;
      transform-origin: 1px 1px;
    }

    &::before {
      transform: translateX(-50%) translateY(-50%)
        rotateZ(-45deg);
    }

    &::after {
      transform: translateX(-50%) translateY(-50%)
        rotateZ(45deg);
    }
  }

  .bar {
    position: absolute;
    top: 0;
    right: 0;
    width: 3px;
    height: 100%;
    cursor: col-resize;
  }
}

.line-split {
  width: 100%;
  height: 1px;
  background: #ffffff;
  opacity: 0.1;
}

.bimNav {
  &-title {
    display: flex;
    background: url('../../../assets/bim/bim_right_top@2x.png');
    height: 56px;
    line-height: 56px;

    > div {
      margin-right: 10px;
      /*padding-bottom: 10px;*/
      cursor: pointer;
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: bold;
      color: #d2e6f0;

      &:first-child {
        margin-left: 36px;
      }
    }

    .is-active {
      //background: url('../../../assets/bim/floor_check@2x.png');
      //background-size: 100% 100%;
      color: rgba(26, 217, 255, 1);
    }
  }
}
</style>
